<template>
  <el-select
    v-model="currentValue"
    filterable
    clearable
    remote
    placeholder="请输入商品品牌"
    :remote-method="querySearchAsync"
    :loading="loading"
    @change="handleSelect"
    @clear="clear"
    style="width: 100%"
  >
    <el-option
      v-for="item in datas"
      :key="item.id"
      :label="item.name"
      :value="item.id">
      <slot>
        <span style="float: left">{{ item.name }}</span>
      </slot>
    </el-option>
  </el-select>
</template>
<script>
  import AdminService from 'src/service/admin'
  import emitter from 'src/components/emitter'

  export default {
    name: 'HBrandChoose',
    mixins: [emitter],
    data() {
      return {
        currentValue: this.value,
        loading: false,
        datas: [],
        search: {
          name: null,
          pagination: {
            total: 0,
            page: 1,
            limit: 20
          },
          isShow: 1,
          status: 1,
          orderBy: 'id'
        }
      }
    },
    props: {
      value: {
        type: Number
      },
      validateEvent: {
        type: Boolean,
        default: true
      },
    },
    watch: {
      value(curVal, oldVal) {
        this.currentValue = curVal
        if (curVal == '') {
          curVal == null
        }
        if (curVal === oldVal) {
          return
        }
        const me = this

        const existValue = me.datas.filter(data => {
          return data.id == curVal
        })

        if (existValue.length == 0) {
          AdminService.brandById(this.value).then(data => {
            if (data != null) {
              me.datas = data.datas
            }
          })
        }
      }
    },
    methods: {
      handleSelect(item) {
        if (item == '') {
          this.$emit('input', null)
        } else {
          this.$emit('input', item)
        }
        this.$emit('change', item)
        this.dispatch('ElFormItem', 'el.form.change', [item])
      },
      clear() {
        this.$emit('input', null)
        this.$emit('change', null)
        this.dispatch('ElFormItem', 'el.form.change', [null])
      },
      querySearchAsync(queryString, cb) {
        const me = this
        if (queryString !== undefined && queryString !== '') {
          me.search.name = queryString
        } else {
          me.search.name = null
        }
        AdminService.brandSearch(me.search).then(data => {
          if (data != null) {
            me.datas = data.datas
          }
        })
      }
    },
    mounted: function () {
      const me = this
      if (me.value != null && me.value != '') {
        AdminService.brandById(this.value).then(data => {
          if (data != null) {
            me.datas = data.datas
          }
        })
      } else {
        this.querySearchAsync(null);
      }
    }
  }
</script>
